package cn.lijiajia3515.cairo.auth.modules;

import cn.lijiajia3515.cairo.core.business.AuthBusiness;
import cn.lijiajia3515.cairo.core.exception.BusinessException;
import cn.lijiajia3515.cairo.domain.CairoAccount;
import cn.lijiajia3515.cairo.security.authentication.CairoAuthentication;
import cn.lijiajia3515.cairo.security.oauth2.jwt.CairoJwtPrincipal;
import cn.lijiajia3515.cairo.security.oauth2.resource.server.authentication.CairoJwtAuthenticationToken;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class IndexApi {

	@GetMapping("/authentication")
	@PreAuthorize("isAuthenticated()")
	public CairoAuthentication authentication(Authentication authentication) {
		if (authentication instanceof CairoAuthentication) {
			// self
			return (CairoAuthentication) authentication;
		} else if (authentication instanceof CairoJwtAuthenticationToken) {
			// oauth2 resource jwt
			CairoJwtPrincipal principal = (CairoJwtPrincipal) authentication.getPrincipal();
			return CairoAuthentication.builder()
				.id(principal.getAccount().getId())
				.login(principal.getAccount().getLogin())
				.email(principal.getAccount().getEmail())
				.phoneNumber(principal.getAccount().getPhoneNumber())
				.nickname(principal.getAccount().getNickname())
				.avatarUrl(principal.getAccount().getAvatarUrl())
				.departments(principal.getAccount().getDepartments())
				.roles(principal.getAccount().getRoles())
				.authorities(authentication.getAuthorities())
				.build();
		} else {
			throw new BusinessException("凭证不可解析, 请联系管理员", AuthBusiness.Bad);
		}
	}

	@GetMapping(value = "/account")
	@PreAuthorize("isAuthenticated()")
	public CairoAccount userinfo(@AuthenticationPrincipal Object principal) {
		if (principal instanceof CairoJwtPrincipal) {
			return ((CairoJwtPrincipal) principal).getAccount();
		} else {
			throw new BusinessException("凭证不可解析, 请联系管理员", AuthBusiness.Bad);
		}
	}

	@GetMapping("/test")
	@PreAuthorize("hasAuthority('a')")
	public String a() {
		return "a";
	}

}
